{% extends "base.html" %}

{% block header%}
<title>查询编辑</title>
<style type="text/css">
	.filed-detailed {
		position: absolute;
		right: 10px;
		width: 20%;
		z-index: 999;
	}
	.add_filed{
		cursor: pointer;
	}

</style>
<script type="text/javascript">

	function get_log_def_for_def_key(defLogKey){
		return def_fiels[defLogKey]
	}

	function make_log_def_checkbox(defLogId){
		var checkbox = $('<input>',{"type":"checkbox"})

	}

	// 模版编辑
	{#function open_edit_template(){#}
	{#	var tpls = $('[name="template_name"]').val()#}
	{#	if (!tpls){return}#}
	{#	tpls = tpls.split(',')#}
    {##}
	{#	for (var i in tpls) {#}
	{#		var tpl_name =  tpls[i]#}
	{#		if(tpl_name){#}
	{#		window.open('/query/edit?edit_type=query&template_name='+ tpl_name,Math.random()*1000,'height=600,width=800,resizable=yes,scrollbars=yes,status=yes')#}
	{#		}#}
	{#	}#}
	{#}#}





// 增加字段
$(document).on('click','.add_filed',function(){
	var This = $(this)
	var text = This.find('.filed_name').text()
	var selectInputEle = $('[name="select"]')
	var selectText = selectInputEle.val()

	if (selectText.indexOf(text)<0) {
		selectText += ',' + text + ','
	}
	selectText = selectText.trim().replace(/^,|,$/g,'')

	selectInputEle.val(selectText)
})
$(function($){

	function FieldEditor(){
		this.cont = $('#field_cont')
		this.textarea = $('[name="field_config"]')

		this.add = function(){
			this.cont.find('.field_config:last').clone().appendTo(this.cont)
		}

		this.get_json_config = function(){
			var config = {}
			this.cont.find('.field_config').each(function(i,ele){
				var This  = $(ele)

				var bind_name = This.find('[name="bind_name"]').val().trim(),
					name = This.find('[name="key_name"]').val().trim(),
					dict = This.find('[name="dict"]').val().trim(),
					sort = This.find('[name="sort"]').is(":checked"),
					search = This.find('[name="search"]').is(":checked"),
					multiple = This.find('[name="multiple"]').is(":checked"),
					fixed = This.find('[name="fixed"]').is(":checked"),
					single = This.find('[name="single"]').is(":checked"),
					merge_value = This.find('[name="merge_value"]').is(":checked"),
					order_num = This.find('[name="order_num"]').val()
					if (bind_name ) {
						config[bind_name] = {
											"name":name,
											"dict":dict,
											"sort":sort,
											"multiple":multiple,
											"search":search,
											"merge_value":merge_value,
											"single":single,
											"fixed":fixed,
											"order_num" :parseInt(order_num ? order_num : 99)
											}
					}

			})
			return JSON.stringify(config)

		}
		this.save = function(){
			var config = this.get_json_config()
			this.textarea.val(config)

		}
	}

	var field_editor = new FieldEditor()

	$('#add_field_config').click(function(event) {
		field_editor.add()
	});

	$('#show_config_btn').click(function(e){
		field_editor.save()
		field_editor.textarea.show()
		field_editor.cont.hide()
	})

	$('#save_query_btn').click(function(e){
		if (field_editor.textarea.is(':hidden')) {
			$('#show_config_btn').click()
		}
		$('#query_form').submit();
	})

	$('#show_cron_info').click(function(e){
	    var is_show = $('#show_cron_info').is(":checked")
        if(is_show) {
            $('.cron_line').show()
        }else{
            $('.cron_line').hide()
        }

	})
});

</script>
{% endblock %}

{% block content %}
<div class="bar">
	<a href="/query/list" >查询列表</a> -> 查询编辑
	<div class="buttons">
		<a href="/query/view?qid={{model.id}}" target="_blank">查询</a>
		<a  id="save_query_btn" class="">保存</a>
	</div>
</div>



<form id="query_form" action="/query/save?query_id={{model.id}}" method="post">
	<table class="form" >
    		<tr>
			<th>父级菜单：</th><td>
			<select name="parent_id" class="menu_select" >
                <option value="-1" >默认</option>
				<option value="0" {%if current_menu.parent_id == 0 %} selected="selected" {%endif%}>顶级</option>
					{%for item in list_menu%}
						{%ifnotequal item.id menu.id%}
						<option value="{{item.id}}" {%ifequal item.id current_menu.parent_id%}selected="selected"{%endifequal%}>{{item.name}}</option>
						{%endifnotequal%}
					{%endfor%}
			</select>
			<input placeholder="搜索" style="width:50px;" type="text" value="" class="menu_select_input" onkeyup="search_dbl_list('menu_select','menu_select_input')">
            <span style="color:blue">默认是保存在查询权限下</span>
		</td>
		</tr>

	{%if model.id %}
	<tr>
		<th>查询id</th><td><input type="text" name="save_id" value="{{model.id}}" {% if model.id and not is_copy %} readonly {%endif%} size="10" /><span style="color:red">没事别随便改我！</span></td>
	</tr>
	{%endif%}
	<tr>
		<th>查询说明：</th>
		<td><input type="text" name="name" value="{{model.name}}" size="50" /></td>
	</tr>
	<tr>
		<th>查询字段：</th>
		<td><input type="text" name="select" style="width:95%" value="{{model.select}}" />
			<div id="filed_area">

			</div>
		</td>
	</tr>
{#	<tr>#}
{#		<th>字段定义:</th>#}
{#		<td>#}
{#			<a id="add_field_config" href="javascript:;" >[添加字段定义]</a>#}
{#			<a id="show_config_btn" href="javascript:;" >[查看配置]</a>#}
{#		</td>#}
{#	</tr>#}
{#	<tr>#}
{#		<th></th>#}
{#		<td>#}
{#			<div id="field_cont">#}
{#				{% for n,c in model.field_config.items%}#}
{#				<div class="field_config">#}
{#					<span class="field_config_cont">#}
{#					绑定名:<input type="text" name="bind_name" value="{{n}}" style="width:100px;">#}
{#					字段名:<input type="text" name="key_name" value="{{c.name}}" style="width:100px;">#}
{#					映射字典:#}
{#					<textarea name="dict" value="{{c.dict}}" style="width:150px;min-height:14px"  placeholder="字典定义名" select_key="dict_key">{{c.dict}}</textarea>#}
{#                    <span>解析json数据格式为:[数据库存在的字典key,{自己定义的字典},支持多种组合]</span>#}
{##}
{#					<!-- <input type="text" name="dict" value="{{c.dict}}" style="width:50%" select_key="dict_key"> -->#}
{#					<br>#}
{#					<label><input type="checkbox" name="sort" {%if c.sort%}checked="checked"{%endif%}> 排序</label>#}
{#					<label><input type="checkbox" name="search" {%if c.search%}checked="checked"{%endif%}> 条件</label>#}
{#					<label><input type="checkbox" name="multiple" {%if c.multiple%}checked="checked"{%endif%}> 多选</label>#}
{#					<label><input type="checkbox" name="single" {%if c.single %}checked="checked"{%endif%}> 单选</label>#}
{#					<label><input type="checkbox" name="fixed" {%if c.fixed%}checked="checked"{%endif%}> 定值(开关)</label>#}
{#					<label><input type="checkbox" name="merge_value" {%if c.merge_value%}checked="checked"{%endif%}> 合并值</label>#}
{#					次序:<input type="number" name="order_num" value="{{c.order_num}}" class="input-mini input-number">#}
{#					</span>#}
{#					<a href="javascript:;" onclick="if ($('.field_config').length>1) $(this).parent().remove()">X</a>#}
{#				</div>#}
{#				{% endfor %}#}
{#			</div>#}
{#			<textarea name="field_config" style="display:none"></textarea>#}
{#		</td>#}
{#	</tr>#}

<tr>
	<th>查询条件：</th><td><input  type="text" name="where" size="50" value="{{model.where}}" /> 例如:字段名=值 支持 and or</td>
</tr>
<tr>
	<th>排序字段：</th><td><input type="text" name="order" value="{{model.order}}" />
	<select name="order_type">
	<option value="0"{%ifequal model.order_type 0%}selected="selected"{%endifequal%}>升序</option>
	<option value="1"{%ifequal model.order_type 1%}selected="selected"{%endifequal%}>降序</option>
	</select>
</td>
</tr>

{#<tr>#}
{#	<th>模版名</th>#}
{#	<td>#}
{#		<input type="text" name="template_name" select-key="query_template_name" value="{{model.template_name}}"/>#}
{#			<a  href="javascript:open_edit_template()">#}
{#		{% if model.template_name%}#}
{#			编辑模版文件#}
{#		{%else%}#}
{#			新建模版文件#}
{#		{%endif%}#}
{#	</a>#}
{#	</td>#}
{#</tr>#}

<tr>
	<th>SQL语句：</th>
	<td style="border:1px solid gray;width:400px">

	<textarea id="sql_cont"  name="sql" >{{model.sql}}</textarea>

	</td>
</tr>
<tr>
	<th>其他SQL语句：(用作ftoot)</th>
	<td style="border:1px solid gray">
	<textarea id="other_sql_cont"  name="other_sql" >{%if model.other_sql%}{{model.other_sql}}{%else%}{%endif%}</textarea>
	</td>
</tr>
{#<tr>#}
{#	<th>缓存时间(秒,0默认不设缓存)：</th>#}
{#	<td>#}
{#		<input type="text" name="cache_valid" value="{{model.cache_validate}}" />#}
{#	</td>#}
{#</tr>#}
<tr>
	<th>查询备注:</th>
	<td><textarea name="remark">{{model.remark}}</textarea>

	</td>
</tr>
<tr>
	<th>帮助:</th>
	<td>
		<div class="alert alert-info">
				<p>注意:</p>
				<p>中央类查询的时间格式要加两个百分号,即:DATE_FORMAT(log_time,'%%Y-%%m-%%d %%H 点')</p>
				<p>取开始时间: {%templatetag  openvariable%}sdate{%templatetag  closevariable%}</p>
				<p>取结束时间: {%templatetag  openvariable%}edate{%templatetag  closevariable%}</p>
{#                <p>取开始时间: {%templatetag  openvariable%}sd{%templatetag  closevariable%}</p>#}
{#				<p>取结束时间: {%templatetag  openvariable%}ed{%templatetag  closevariable%}</p>#}
{#				<hr>#}
{#				字段定义:#}
{#					排序:此列可以排序,指定的字段名必须与SQL语句的字段名相同,#}
{#					条件:页面显示条件#}
{#					多选:多选条件,如果有指定映射字典则下拉多选控件,否则为textarea多选输入#}
{#					定值(开关):控件为checkbox勾选则传递定值,定值在映射字典填写#}
{#					单选:控件为radio,必选#}
		</div>
	</td>
</tr>

{#<tr>#}
{#    <th>开启中间表定时任务：</th>#}
{#    <td>#}
{#    <label><input id="show_cron_info" name="open_cron" type="checkbox" {%if model.open_cron == 1%}checked="checked"{%endif%}/>#}
{#        开启中间表定时任务模式，将定时获取数据插入中间表</label>#}
{#    </td>#}
{#</tr>#}
<tr  class="cron_line">
    <th>定时任务key：</th>
    <td>
        <input type="text" name="cron_key" size="32" {%if model.cron_key%}value="{{model.cron_key}}" {%endif%}/>
        必须唯一，建议与中间表名一致
    </td>
</tr>
{#<tr class="cron_line">#}
{#	<th>查询数据路径：</th>#}
{#    <td>#}
{#        <select name="cron_data_source">#}
{#        <option value="0"{%ifequal model.cron_data_source 0%}selected="selected"{%endifequal%}>log库</option>#}
{#        <option value="1"{%ifequal model.cron_data_source 1%}selected="selected"{%endifequal%}>央库</option>#}
{#        </select>#}
{#    </td>#}
{#</tr>#}
<tr class="cron_line">
	<th>查询数据的sql：</th>
	<td><textarea name="cron_select_sql" >{%if model.cron_select_sql%}{{model.cron_select_sql}}{%else%}{%endif%}</textarea>
	<p>* 必须要有自定义server_id，sdate，edate列，不能有其他自定义列</p>
    </td>
</tr>
<tr class="cron_line">
    <th>创建中间表的sql：</th>
    <td><textarea name="cron_create_sql" >{%if model.cron_create_sql%}{{model.cron_create_sql}}{%else%}{%endif%}</textarea>
    <p>* 必须包含id(默认自增)，server_id，update_time(默认当前时间)字段，以及一个包含server_id在内的UNIQUE KEY</p>
    </td>
</tr>
<tr class="cron_line">
    <th>向中间表插入数据的sql：</th>
    <td><textarea name="cron_insert_sql" >{%if model.cron_insert_sql%}{{model.cron_insert_sql}}{%else%}{%endif%}</textarea>
    <p>* 按查询sql的顺序插入数据，不包含id和update_time，必须用DUPLICATE KEY写法</p>
    </td>
</tr>
<tr class="cron_line">
    {%if model.cron_last_time%}
    <th>任务最近执行时间：</th>
    <td>
        {{model.cron_last_time}}
    </td>
    {%endif%}
</tr>
<tr class="cron_line">
    <th>历史数据是否入库：</th>
    <td>
         {%if model.cron_old_data%}已入库{% else %}未完成…{%endif%}
    </td>
</tr>
</table>
</form>

{% with '/static/js/codemirror' as URL %}
<script src={{URL}}/lib/codemirror.js></script>
<link rel="stylesheet" href="{{URL}}/lib/codemirror.css" />
<style type="text/css">
      .CodeMirror {
        border: 1px solid #eee;
        height: auto;

      }
</style>
<script src="{{URL}}/mode/sql/sql.js"></script>
<script type="text/javascript">
window.onload = function() {
	var mime = 'text/x-mariadb';
	if (window.location.href.indexOf('mime=') > -1) {
		mime = window.location.href.substr(window.location.href.indexOf('mime=') + 5);
	}
	var sql_editor = CodeMirror.fromTextArea(document.getElementById('sql_cont'), {
		mode: mime,
		indentWithTabs: true,
		smartIndent: true,
		lineNumbers: true,
		matchBrackets : true,
		lineWrapping: true,
		//autofocus: true,
		//viewportMargin: Infinity,
		tabSize: 4,
	});
	var other_sql_editor = CodeMirror.fromTextArea(document.getElementById('other_sql_cont'), {
		mode: mime,
		indentWithTabs: true,
		smartIndent: true,
		lineNumbers: true,
		matchBrackets : true,
		//autofocus: true,
		lineWrapping: true,
		tabSize: 4,
	});
    var show_cron_table = {{ model.open_cron }};
    if(show_cron_table !== 1){
        $('.cron_line').hide();
    }
};
</script>

{%endwith%}
{% endblock %}